const express = require('express');
const router = express.Router();
const fn = require("../db_sql")
const utility = require("utility")

//    获取
router.get("/userinfo", async function (req, res) {
    // 获取当前用户登录的信息
    try {
        let arr = await fn(`select * from user where id=?`, req.user.userId)
        res.send({
            "status": 0,
            "message": "获取用户信息成功！",
            data: arr[0]
        });
    } catch (error) {
        res.send({ //无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "获取用户信息失败！",
        });
    }
});

//    更新
router.post("/userinfo", async function (req, res) {

    try {
        await fn(`update user set ? where id=?`, [req.body, req.user.userId])
        res.send({
            "status": 0,
            "message": "修改用户信息成功！",
        });
    } catch (error) {
        res.send({ //无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "修改用户信息失败！",
        });
    }
    // 2.把数据添加数据库

});


//    密码
router.post("/updatepwd", async function (req, res) {

    req.body.oldpassword = utility.md5(req.body.oldpassword)
    req.body.newpassword = utility.md5(req.body.newpassword)

    try {
        await fn("select *from user where password=? and id=?", [req.body.oldpassword, req.user.userId])
        await fn(`update user set password=? where Id=?`, [req.body.newpassword, req.user.userId])
        res.send({
            "status": 0,
            "message": "修改密码成功！",
        });

    } catch (error) {
        res.send({ // 无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "修改密码失败！",
        });
    }
    // 2.把数据添加数据库

});

//    头像：
router.post("/update/avatar", async function (req, res) {
    // 复习：post :   req.body
    //      动态接口：req.params
    //       get  :   req.query 
    try {
        await fn(`update user set user_pic=? where id=?`, [req.body.avatar, req.user.userId])
        res.send({
            "status": 0,
            "message": "更新头像成功！",
        });
    } catch (error) {
        res.send({ // 无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "更新头像失败！",
        });
    }

});

// 固定4：导出模块。主app.js内部需要这个JS文件的内容！
module.exports = router;